#!/bin/sh
# Download and build latest version of ARM Trusted Firmware

PLAT="${1}" # For example "sun50i_a64"
TUPLE="${2}" # For example "aarch64-linux-gnu"

set -ex

ATF_GIT_URL_DEFAULT="https://github.com/ARM-software/arm-trusted-firmware.git"

if [ ! -z "${ATF_GIT_REV}" ]
then
	git clone --depth 1 \
	          --reference-if-able "${WORKDIR}/arm-trusted-firmware" \
	          --branch "${ATF_GIT_REV}" \
	          "${ATF_GIT_URL:-${ATF_GIT_URL_DEFAULT}}" arm-trusted-firmware
else
	git clone --depth 1 \
	          --reference-if-able "${WORKDIR}/atf" \
	          "${ATF_GIT_URL:-${ATF_GIT_URL_DEFAULT}}" arm-trusted-firmware
fi

# Collect version of ATF
(echo -n atf,; git -C arm-trusted-firmware describe --tags --always --abbrev=10) >> versions.csv

# Step into ATF directory
cd arm-trusted-firmware

# Apply patches
if [ -d "${ATF_PATCHES_DIR}" ]; then
	git apply "${ATF_PATCHES_DIR}"/*.patch || :
fi

# CROSS_COMPILE must point to a valid compiler path prefix
export CROSS_COMPILE=$(dirname $(which "${TUPLE}-gcc"))/"${TUPLE}-"

# Build ATF
make ${MAKEFLAGS:--j$(nproc)} PLAT="${PLAT}" DEBUG=1 bl31
